/**
 * Created by oschina on 2014/8/3.
 */
'use strict';
angular.module('tweetMapApp').controller('tweetCtrl', function ($scope) {
    var vm = $scope.vm = {};
    vm.items = [
        {
            userId:1,
            userName:'红薯',
            userImg:'http://static.oschina.net/uploads/user/0/12_50.jpg?t=1387864442000',
            tweet:'做开源中国得让自己内心变得非常强大，各种被喷，只好无视',
            time:'1分钟前',
            locationX:114.138372,
            locationY:22.530595
        },
        {
            userId:2,
            userName:'叶秀兰',
            userImg:'http://static.oschina.net/uploads/user/432/865233_50.jpg?t=1388546891000',
            tweet:'@北_木 大早上起来煮了超有爱的红枣黑豆浆，好喝！顾着喝忘记拍照了1',
            city:'北京',
            time:'2分钟前',
            locationX:114.138372,
            locationY:23.530595
        },
        {
            userId:2,
            userName:'火蚁',
            userImg:'http://static.oschina.net/uploads/user/126/253900_50.jpg?t=1407925427000',
            tweet:'动弹地图2',
            city:'北京',
            time:'2分钟前',
            locationX:113.138372,
            locationY:23.630595
        }
        ,{
            userId:2,
            userName:'Mr_Tank_',
            userImg:'http://static.oschina.net/uploads/user/296/593105_50.jpg?t=1406602959000',
            tweet:'@我@我@我',
            city:'北京',
            time:'2分钟前',
            locationX:113.038372,
            locationY:22.550595
        },{
            userId:2,
            userName:'阿娇OSC',
            userImg:'http://static.oschina.net/uploads/user/882/1765084_50.jpg?t=1403105440000',
            tweet:'在家吃完晚饭了，想到小伙伴们应该还没有下班',
            city:'北京',
            time:'2分钟前',
            locationX:113.638372,
            locationY:22.630595
        }
        ,{
            userId:2,
            userName:'小编辑',
            userImg:'http://static.oschina.net/uploads/user/2/5189_50.jpg',
            tweet:'为什么你们最近都不 @ 我了呢？',
            url: 'http://my.oschina.net/xiaobian',
            city:'北京',
            time:'2分钟前',
            locationX:113.618372,
            locationY:22.610595
        },{
            userId:2,
            userName:'永和',
            userImg:'http://static.oschina.net/uploads/user/471/943418_50.jpg?t=1404658402000',
            tweet:'蓝翔校长毕业典礼上的一席话：“同学们，咱们蓝翔技校就是实打实的学本领，咱们不玩虚的，你学挖掘机就把地挖好，你学厨师就把菜做好，你学裁缝就把衣服做好。咱们蓝翔如果不踏踏实实学本事，那跟清华北大还有什么区别呢？”',
            url: 'http://my.oschina.net/xiaobian',
            city:'北京',
            time:'2分钟前',
            locationX:113.668372,
            locationY:22.670595
        }
    ];

    vm.addItem = function() {
        Api.user(function(user) {
            if (!user) {
                Api.rcookie('user');
            }else {

                var item = {
                    userId: user.id,
                    userName: user.name,
                    userImg: user.avatar,
                    tweet: vm.tweet,
                    city: user.location,
                    time: '刚刚',
                    url: user.url,
                    locationX: locationX.innerHTML,
                    locationY: locationY.innerHTML
                }
                vm.items.push(item);
                tweetMarker(item,vm);
                vm.mapObj.plugin(["AMap.MarkerClusterer"],function(){
                    vm.cluster = new AMap.MarkerClusterer(vm.mapObj,vm.markers);
                });
                vm.mapObj.setZoomAndCenter(14,new AMap.LngLat(locationX.innerHTML,locationY.innerHTML));

                Api.pop_tweet(vm.tweet+"我的坐标："+locationX.innerHTML+" "+locationY.innerHTML);
            }
        });


    };

    vm.mapObj= new AMap.Map("iCenter",{
        center: new AMap.LngLat(111.39, 33.9),
        zoom:5 //地图显示的缩放级别
    });

    //地图中添加地图操作ToolBar插件
    vm.mapObj.plugin(["AMap.ToolBar"],function(){
        vm.toolBar = new AMap.ToolBar(); //设置地位标记为自定义标记

        vm.mapObj.addControl(vm.toolBar);
        //定位发动弹的人的位置

        AMap.event.addListener(vm.toolBar,'location',function callback(e){
            vm.locationInfo = e.lnglat;
        });


    });

    vm.mapObj.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            maximumAge: 0,           //定位结果缓存0毫秒，默认：0
            convert: true,           //自动偏移坐标，偏移后的坐标为高德坐标，默认：true
            showButton: true,        //显示定位按钮，默认：true
            buttonPosition: 'LB',    //定位按钮停靠位置，默认：'LB'，左下角
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            showMarker: false,        //定位成功后在定位到的位置显示点标记，默认：true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围，默认：true
            panToLocation: false,     //定位成功后将定位到的位置作为地图中心点，默认：true
            zoomToAccuracy:false      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        });
        vm.mapObj.addControl(geolocation);
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
        geolocation.getCurrentPosition();
    });



    vm.cluster;
    vm.markers= [];
    for(var ele in vm.items) {
        tweetMarker(vm.items[ele],vm);
    }
    vm.mapObj.plugin(["AMap.MarkerClusterer"],function(){
        vm.cluster = new AMap.MarkerClusterer(vm.mapObj,vm.markers);
    });

});

//添加带文本的点标记覆盖物
function tweetMarker(item,vm){
   var  markerContent="<div><img style='border-radius:50%; overflow:hidden;' src='"+item.userImg+"' /></div>"
    var marker = new AMap.Marker({
        map:vm.mapObj,
        position:new AMap.LngLat(item.locationX,item.locationY), //基点位置

        draggable:false,  //是否可拖动
        content:markerContent   //自定义点标记覆盖物内容
    });

    var info = [];
    info.push("<div>");
    info.push("<b>"+item.userName+":</b>");
    info.push(item.tweet);
    info.push("</div>");
    var infoWindow = new AMap.InfoWindow({
        content:info.join("<br/>"),  //使用默认信息窗体框样式，显示信息内容
        offset:new AMap.Pixel(20,-27)
    });


        //mouseover,显示详细动弹信息
        AMap.event.addListener(marker, "mouseover", function () {
            infoWindow.open(vm.mapObj, new AMap.LngLat(item.locationX, item.locationY));
        });
        //mouseout,只显示头像
        AMap.event.addListener(marker, "mouseout", function () {
            infoWindow.close();
        });

     vm.markers.push(marker);


}

/*
 *解析定位结果
 */
function onComplete (data) {

    locationX.innerHTML=data.position.getLng();
    locationY.innerHTML=data.position.getLat();

};
/*
 *解析定位错误信息
 */
function onError (data) {
    var str = '<p>定位失败</p>';
    str += '<p>错误信息：'
    switch(data.info) {
        case 'PERMISSION_DENIED':
            str += '浏览器阻止了定位操作';
            break;
        case 'POSITION_UNAVAILBLE':
            str += '无法获得当前位置';
            break;
        case 'TIMEOUT':
            str += '定位超时';
            break;
        default:
            str += '未知错误';
            break;
    }
    str += '</p>';
    locationInfo.innerHTML=str;
};


